<template>
  <div class="appointment-container">
    <div class="appointment-header">
      <h1 class="page-title">参观预约</h1>
      <p class="page-subtitle">为了给您提供更好的参观体验，请提前预约</p>
    </div>

    <el-card class="appointment-card">
      <el-steps :active="currentStep" finish-status="success" align-center>
        <el-step title="选择日期" icon="Calendar" />
        <el-step title="填写信息" icon="User" />
        <el-step title="确认预约" icon="Check" />
      </el-steps>

      <!-- 第一步：选择日期和时间段 -->
      <div v-if="currentStep === 0" class="step-content">
        <div class="date-picker-section">
          <h3>选择参观日期</h3>
          <el-date-picker
            v-model="appointmentDate"
            type="date"
            :disabled-date="disabledDate"
            placeholder="请选择参观日期"
            format="YYYY年MM月DD日"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
          />
        </div>

        <div class="time-slot-section">
          <h3>选择参观时段</h3>
          <p class="time-slot-tip">每个时段限额100人，请选择合适的时间</p>
          <el-radio-group v-model="timeSlot" class="time-slot-group">
            <el-radio-button 
              v-for="slot in availableTimeSlots" 
              :key="slot.value"
              :label="slot.value"
              :disabled="slot.remaining <= 0"
            >
              {{ slot.label }}
              <div class="slot-remaining">剩余：{{ slot.remaining }}个名额</div>
            </el-radio-button>
          </el-radio-group>
        </div>
      </div>

      <!-- 第二步：填写个人信息 -->
      <div v-if="currentStep === 1" class="step-content">
        <el-form
          ref="formRef"
          :model="visitorForm"
          :rules="formRules"
          label-width="100px"
          class="visitor-form"
        >
          <el-form-item label="姓名" prop="name">
            <el-input v-model="visitorForm.name" placeholder="请输入真实姓名" />
          </el-form-item>

          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="visitorForm.phone" placeholder="请输入手机号码" />
          </el-form-item>

          <el-form-item label="证件类型" prop="idType">
            <el-select v-model="visitorForm.idType" placeholder="请选择证件类型">
              <el-option label="身份证" value="身份证" />
              <el-option label="护照" value="护照" />
              <el-option label="港澳通行证" value="港澳通行证" />
            </el-select>
          </el-form-item>

          <el-form-item label="证件号码" prop="idNumber">
            <el-input v-model="visitorForm.idNumber" placeholder="请输入证件号码" />
          </el-form-item>

          <el-form-item label="参观人数" prop="visitorCount">
            <el-input-number 
              v-model="visitorForm.visitorCount" 
              :min="1" 
              :max="5"
              controls-position="right"
            />
            <span class="form-tip">单次最多预约5人</span>
          </el-form-item>

          <el-form-item label="备注" prop="remarks">
            <el-input
              v-model="visitorForm.remarks"
              type="textarea"
              rows="3"
              placeholder="如有特殊需求请在此说明"
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 第三步：确认信息 -->
      <div v-if="currentStep === 2" class="step-content">
        <div class="confirmation-card">
          <h3>预约信息确认</h3>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="参观日期">
              {{ formatDate(appointmentDate) }}
            </el-descriptions-item>
            <el-descriptions-item label="参观时段">
              {{ getTimeSlotLabel(timeSlot) }}
            </el-descriptions-item>
            <el-descriptions-item label="预约人">
              {{ visitorForm.name }}
            </el-descriptions-item>
            <el-descriptions-item label="联系电话">
              {{ visitorForm.phone }}
            </el-descriptions-item>
            <el-descriptions-item label="参观人数">
              {{ visitorForm.visitorCount }}人
            </el-descriptions-item>
          </el-descriptions>

          <div class="notice-section">
            <h4>温馨提示：</h4>
            <ul>
              <li>请在预约时间前15分钟到达博物馆</li>
              <li>请携带有效证件，以便核验身份</li>
              <li>如需取消预约，请提前24小时操作</li>
              <li>特殊人群请携带相关证明文件</li>
            </ul>
          </div>
        </div>
      </div>

      <!-- 步骤控制按钮 -->
      <div class="step-actions">
        <el-button v-if="currentStep > 0" @click="previousStep">上一步</el-button>
        <el-button
          v-if="currentStep < 2"
          type="primary"
          @click="nextStep"
        >
          下一步
        </el-button>
        <el-button
          v-else
          type="primary"
          :loading="submitting"
          @click="submitAppointment"
        >
          确认预约
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Calendar, User, Check } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { getEnabledTimeSlots, getTimeSlotStatistics } from '@/api/timeSlot'
import { addAppointment } from '@/api/appointment'
import { useStore } from 'vuex'

// 获取用户信息
const store = useStore()
const userInfo = computed(() => store.getters.userInfo)

// 步骤控制
const currentStep = ref(0)
const appointmentDate = ref(dayjs().format('YYYY-MM-DD')) // 设置默认日期为今天
const timeSlot = ref('')
const submitting = ref(false)

// 可用时间段
const availableTimeSlots = ref([])

// 访客表单
const formRef = ref(null)
const visitorForm = ref({
  name: '',
  phone: '',
  idType: '身份证',
  idNumber: '',
  visitorCount: 1,
  remarks: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  idNumber: [
    { required: true, message: '请输入证件号码', trigger: 'blur' }
  ],
  visitorCount: [
    { required: true, message: '请选择参观人数', trigger: 'change' }
  ]
}

// 禁用日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7 || // 今天之前
         time.getDay() === 1 // 周一闭馆
}

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format('YYYY年MM月DD日')
}

// 获取时间段标签
const getTimeSlotLabel = (value) => {
  const slot = availableTimeSlots.value.find(s => s.value === value)
  return slot ? slot.label : ''
}

// 获取可用时间段
const fetchTimeSlots = async () => {
  try {
    const response = await getEnabledTimeSlots()
    availableTimeSlots.value = response.map(slot => ({
      label: `${slot.startTime} - ${slot.endTime}`,
      value: slot.id.toString(),
      remaining: slot.maxVisitors,
      maxVisitors: slot.maxVisitors
    }))
    
    // 如果已选择日期，获取时间段统计信息
    if (appointmentDate.value) {
      await fetchTimeSlotStatistics(appointmentDate.value)
    }
  } catch (error) {
    ElMessage.error('获取时间段信息失败')
  }
}

// 获取时间段统计信息
const fetchTimeSlotStatistics = async (date) => {
  try {
    const statistics = await getTimeSlotStatistics(date)
    // 更新可用时间段的剩余人数
    availableTimeSlots.value = availableTimeSlots.value.map(slot => {
      const statInfo = statistics.find(stat => stat.slotId.toString() === slot.value)
      if (statInfo) {
        return {
          ...slot,
          remaining: statInfo.availableVisitors
        }
      }
      return slot
    })
  } catch (error) {
    ElMessage.error('获取时间段统计信息失败')
  }
}

// 监听日期变化
const handleDateChange = async () => {
  timeSlot.value = '' // 重置已选择的时间段
  if (appointmentDate.value) {
    await fetchTimeSlotStatistics(appointmentDate.value)
  }
}

// 在组件挂载时获取时间段数据
onMounted(() => {
  fetchTimeSlots()
})

// 步骤控制
const nextStep = async () => {
  if (currentStep.value === 0) {
    if (!appointmentDate.value || !timeSlot.value) {
      ElMessage.warning('请选择参观日期和时间段')
      return
    }
    currentStep.value++
  } else if (currentStep.value === 1) {
    await formRef.value.validate((valid) => {
      if (valid) {
        currentStep.value++
      }
    })
  }
}

const previousStep = () => {
  currentStep.value--
}

// 提交预约
const submitAppointment = async () => {
  console.log(userInfo.value);
  
  if (!userInfo.value.userInfo.id) {
    ElMessage.warning('请先登录')
    return
  }

  submitting.value = true
  try {
    const appointmentData = {
      userId: userInfo.value.userInfo.id,
      appointmentDate: appointmentDate.value,
      timeSlotId: timeSlot.value,
      visitorName: visitorForm.value.name,
      visitorPhone: visitorForm.value.phone,
      idType: visitorForm.value.idType,
      idNumber: visitorForm.value.idNumber,
      visitorCount: visitorForm.value.visitorCount,
      remarks: visitorForm.value.remarks
    }

    await addAppointment(appointmentData)
    ElMessage.success('预约成功！')
    
    // 重置表单和步骤
    currentStep.value = 0
    appointmentDate.value = dayjs().format('YYYY-MM-DD') // 设置日期为今天
    timeSlot.value = ''
    visitorForm.value = {
      name: '',
      phone: '',
      idType: '身份证',
      idNumber: '',
      visitorCount: 1,
      remarks: ''
    }
    
    // 重新获取时间段统计数据
    await fetchTimeSlotStatistics(appointmentDate.value)
  } catch (error) {
    ElMessage.error('预约失败，请重试')
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.appointment-container {
  padding: 40px 24px;
  max-width: 1000px;
  margin: 0 auto;
}

.appointment-header {
  text-align: center;
  margin-bottom: 40px;
}

.page-title {
  font-size: 32px;
  color: #2c3e50;
  margin-bottom: 12px;
}

.page-subtitle {
  color: #606266;
  font-size: 16px;
}

.appointment-card {
  padding: 32px;
}

.step-content {
  margin: 40px 0;
}

.date-picker-section,
.time-slot-section {
  margin-bottom: 32px;
}

.date-picker-section h3,
.time-slot-section h3 {
  margin-bottom: 16px;
  color: #2c3e50;
}

.time-slot-tip {
  color: #909399;
  margin-bottom: 16px;
  font-size: 14px;
}

.time-slot-group {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
}

.slot-remaining {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.visitor-form {
  max-width: 600px;
  margin: 0 auto;
}

.form-tip {
  margin-left: 12px;
  color: #909399;
  font-size: 14px;
}

.confirmation-card {
  max-width: 600px;
  margin: 0 auto;
}

.confirmation-card h3 {
  margin-bottom: 24px;
  color: #2c3e50;
}

.notice-section {
  margin-top: 32px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.notice-section h4 {
  color: #2c3e50;
  margin-bottom: 12px;
}

.notice-section ul {
  padding-left: 20px;
  color: #606266;
}

.notice-section li {
  margin-bottom: 8px;
  line-height: 1.5;
}

.step-actions {
  margin-top: 32px;
  text-align: center;
}

.step-actions .el-button {
  margin: 0 8px;
  min-width: 120px;
}

@media (max-width: 768px) {
  .appointment-container {
    padding: 20px 16px;
  }

  .page-title {
    font-size: 24px;
  }

  .appointment-card {
    padding: 16px;
  }

  .time-slot-group {
    grid-template-columns: 1fr;
  }

  .visitor-form {
    padding: 0;
  }
}
</style> 